package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/*
 * Rest模式
 * */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     *
     * @param page     当前页码
     * @param pageSize 每页显示的条数
     * @param name     菜品名称
     * @return
     */
    @GetMapping("page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        //创建分页构造器
        Page<Dish> dishPageInfo = new Page(page, pageSize);
        Page<DishDto> dishDtoPageInfo = new Page<>();
        //创建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加模糊查询条件
        queryWrapper.like(StringUtils.isNotBlank(name), Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(dishPageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(dishPageInfo, dishDtoPageInfo, "records");

        List<Dish> dishList = dishPageInfo.getRecords();
        List<DishDto> dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);

            //对象拷贝
            BeanUtils.copyProperties(item, dishDto);

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPageInfo.setRecords(dishDtoList);

        return R.success(dishDtoPageInfo);
    }

    /**
     * 新增菜品
     *
     * @param dishDto 接受前端参数
     * @return
     */
    @Transactional
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish
        dishService.save(dishDto);

        //保存菜品的口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);

        return R.success("新增成功!");
    }

    /**
     * 修改菜品信息和对应的口味信息的数据回显功能
     * 根据id查询菜品的基本信息和对应的口味信息
     *
     * @param id 菜品id
     * @return
     */
    @Transactional
    @GetMapping("{id}")
    public R<DishDto> selectByIdDishAndDishFlavor(@PathVariable("id") Long id) {
        //根据菜品Id查询菜品的基本信息
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(Dish::getId, id);
        Dish dish = dishService.getOne(dishQueryWrapper);

        //根据菜品Id查询菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorQueryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavorList = dishFlavorService.list(dishFlavorQueryWrapper);

        DishDto dishDto = new DishDto();
        dishDto.setFlavors(flavorList);

        //对象拷贝
        BeanUtils.copyProperties(dish, dishDto);

        return R.success(dishDto);
    }

    /**
     * 根据Id修改菜品信息和对应的口味信息
     *
     * @param dishDto 接受前端数据的参数
     * @return
     */
    @Transactional
    @PutMapping
    public R<String> putDishAndDishFlavor(@RequestBody DishDto dishDto) {
        //根据菜品id修改菜品信息
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(Dish::getId, dishDto.getId());
        dishService.update(dishDto, dishQueryWrapper);

        //根据菜品id查询菜品口味信息,得到菜品口味id
        LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorQueryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorQueryWrapper);

        for (DishFlavor dishFlavor : dishFlavorList) {
            try {
                //根据菜品口味id删除菜品口味的信息
                dishFlavorService.removeById(dishFlavor.getId());
            } catch (Exception e) {
                log.info("删除失败!!!");
                throw new RuntimeException(e);
            }
        }

        //给dishDto.getFlavors()中的DishFlavor的dishId赋值
        for (DishFlavor flavor : dishDto.getFlavors()) {
            if (flavor.getDishId() == null) {
                flavor.setDishId(dishDto.getId());
            }
        }

        //根据菜品id新增菜品口味的信息
        dishFlavorService.saveBatch(dishDto.getFlavors());

        return R.success("修改成功!");
    }

    /**
     * 修改菜品状态
     *
     * @param ids    菜品的id
     * @param status 菜品的状态 0:停售 1:起售
     * @return
     */
    @PostMapping("status/{status}")
    private R<String> updateStatus(Long[] ids, @PathVariable("status") Integer status) {
        Dish dish = new Dish();
        dish.setStatus(status);
        //修改菜品的状态
        for (Long id : ids) {
            try {
                LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Dish::getId, id);
                dish.update(queryWrapper);
            } catch (Exception e) {
                log.info("修改失败!");
                throw new RuntimeException(e);
            }
        }
        return R.success("修改成功!");
    }

    /**
     * 删除菜品(逻辑删除)
     * 删除状态的值为：1,未删除状态的值为：0
     *
     * @param ids 菜品的id
     * @return
     */
    @Transactional
    @DeleteMapping
    public R<String> delete(Long[] ids) {
        //删除菜品
        for (Long id : ids) {
            try {
                LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
                dishService.removeById(id);
                dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, id);
                List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
                for (DishFlavor dishFlavor : list) {
                    dishFlavorService.removeById(dishFlavor.getId());
                }
            } catch (Exception e) {
                log.info("删除失败!");
                throw new RuntimeException(e);
            }
        }
        return R.success("删除成功!");
    }

    /**
     * 根据菜品及套餐分类的Id查询菜品分类对应所有的菜品名称
     * @param categoryId 菜品及套餐分类的Id
     * @return
     */
    @GetMapping("list")
    public R<List<Dish>> getListDishNameById(Long categoryId,String name){
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();

        //添加菜品及套餐分类的Id是否相等条件
        dishQueryWrapper.eq(!StringUtils.isNotBlank(name),Dish::getCategoryId,categoryId);

        //模糊查询
        dishQueryWrapper.like(StringUtils.isNotBlank(name),Dish::getName,name);

        //添加排序条件
        dishQueryWrapper.orderByAsc(Dish::getPrice).orderByDesc(Dish::getUpdateTime);

        return R.success(dishService.list(dishQueryWrapper));
    }
}
